package jgl.vajra.driver.widget.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import androidx.fragment.app.FragmentActivity;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.view.WindowManager;

import jgl.vajra.driver.widget.retrofithelper.rxschedulers.RxSchedulersHelper;
import jgl.vajra.driver.widget.retrofithelper.rxsubscriber.CommonObserver;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;

/**
 * Created by Administrator on 2017/11/23.
 */

public class BitmapUtils {
    public static Bitmap scaleImage(Bitmap bm, int newWidth, int newHeight) {
        if (bm == null) {
            return null;
        }
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                true);
        if (bm != null & !bm.isRecycled()) {
            bm.recycle();
            bm = null;
        }
        return newbm;
    }

    public static Bitmap readBitmapById(int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        InputStream is = UIUtils.getContext().getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    public static Bitmap scaleEmoji(int bm, int newWidth, int newHeight) {
        return scaleImage(readBitmapById(bm), newWidth, newHeight);
    }


    public static void saveFile(final Bitmap bm, final String fileName, final AppCompatActivity activity) {
        io.reactivex.Observable.create(new ObservableOnSubscribe<File>() {
            @Override
            public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                File imageFolderPath = FileUtils.getImageFolderFile();
                if (imageFolderPath == null) emitter.onError(new NullPointerException());
                File jpgFile = new File(imageFolderPath, fileName);
                if (!jpgFile.exists()) {
                    BufferedOutputStream bos = null;
                    try {
                        jpgFile.createNewFile();
                        bos = new BufferedOutputStream(new FileOutputStream(jpgFile));
                        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        emitter.onNext(jpgFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            bos.flush();
                            bos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                } else {
                    emitter.onNext(jpgFile);
                }
            }
        }).compose(RxSchedulersHelper.applyIoTransformer()).subscribe(new io.reactivex.Observer<File>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(File file) {
                ToastUtils.showShort("已保存图片至" + file.getAbsolutePath());
                ImageUitls.savePicRefreshGallery(activity, file);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });


    }

    public static void saveImage(final Bitmap bm, String fileName) {
        File imageFolderPath = FileUtils.getImageFolderFile();
        if (imageFolderPath == null) return;
        File jpgFile = new File(imageFolderPath, fileName);
        if (jpgFile.exists()) {
            jpgFile.delete();
        }
        BufferedOutputStream bos = null;
        try {
            jpgFile.createNewFile();
            bos = new BufferedOutputStream(new FileOutputStream(jpgFile));
            bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bos.flush();
                bos.close();
                bm.recycle();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    public static void saveGoodsCategoryImage(final Bitmap bm, final long fileName) throws Exception {
        saveImage(bm, "goodsCategory_" + fileName + ".png");

    }

    public static float getInitImageScale(String imagePath, FragmentActivity activity) {
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        WindowManager wm = activity.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        // 拿到图片的宽和高
        int dw = bitmap.getWidth();
        int dh = bitmap.getHeight();
        float scale = 1.0f;
        //图片宽度大于屏幕，但高度小于屏幕，则缩小图片至填满屏幕宽
        if (dw > width && dh <= height) {
            scale = width * 1.0f / dw;
        }
        //图片宽度小于屏幕，但高度大于屏幕，则放大图片至填满屏幕宽
        if (dw <= width && dh > height) {
            scale = width * 1.0f / dw;
        }
        //图片高度和宽度都小于屏幕，则放大图片至填满屏幕宽
        if (dw < width && dh < height) {
            scale = width * 1.0f / dw;
        }
        //图片高度和宽度都大于屏幕，则缩小图片至填满屏幕宽
        if (dw > width && dh > height) {
            scale = width * 1.0f / dw;
        }
        return scale;
    }

    public static float getInitImageScale(Bitmap bitmap, FragmentActivity activity) {
        WindowManager wm = activity.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        // 拿到图片的宽和高
        int dw = bitmap.getWidth();
        int dh = bitmap.getHeight();
        float scale = 1.0f;
        //图片宽度大于屏幕，但高度小于屏幕，则缩小图片至填满屏幕宽
        if (dw > width && dh <= height) {
            scale = width * 1.0f / dw;
        }
        //图片宽度小于屏幕，但高度大于屏幕，则放大图片至填满屏幕宽
        if (dw <= width && dh > height) {
            scale = width * 1.0f / dw;
        }
        //图片高度和宽度都小于屏幕，则放大图片至填满屏幕宽
        if (dw < width && dh < height) {
            scale = width * 1.0f / dw;
        }
        //图片高度和宽度都大于屏幕，则缩小图片至填满屏幕宽
        if (dw > width && dh > height) {
            scale = width * 1.0f / dw;
        }
        return scale;
    }

    public static File saveBitmapFile(Bitmap bitmap) {
        File imageFolderPath = FileUtils.getFileFolderFile();
        if (imageFolderPath == null) return null;
        File file = new File(imageFolderPath, System.currentTimeMillis() + ".png");//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            bos.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String bitmap2StrByBase64(File imagePath) {
        Bitmap bit = BitmapFactory.decodeFile(imagePath.getAbsolutePath());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return "data:image/jpg;base64," + Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    public static void saveViewToImage(Context context, View view) {
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        view.setDrawingCacheBackgroundColor(Color.WHITE);
        Observable.create(new ObservableOnSubscribe<File>() {
            @Override
            public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                // 把一个View转换成图片
                Bitmap cachebmp = loadBitmapFromView(view);

                File file = saveBitmapFile(cachebmp);
                cachebmp.recycle();
                emitter.onNext(file);
                emitter.onComplete();
            }
        }).subscribe(new CommonObserver<File>() {
            @Override
            public void onNext(File file) {
                super.onNext(file);
                view.destroyDrawingCache();
                ToastUtils.showShort("已保存图片至" + file.getAbsolutePath());
                ImageUitls.savePicRefreshGallery(context, file);
            }
        });


    }

    private static Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }

    public static void decoderBase64File(String base64Str, String savePath, CommonObserver<File> commonObserver)  {
        Observable.create(new ObservableOnSubscribe<File>() {
            @Override
            public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                File imageFolderFile = FileUtils.getImageFolderFile();
                if (imageFolderFile == null) return;
                File file = new File(imageFolderFile, savePath + ".png");//将要保存图片的路径
                if (!file.exists()) {
                    file.createNewFile();
                }
                byte[] buffer = android.util.Base64.decode(base64Str, Base64.DEFAULT);
                FileOutputStream out = new FileOutputStream(file);
                out.write(buffer);
                out.close();
                emitter.onNext(file);
                emitter.onComplete();
            }
        }).compose(RxSchedulersHelper.applyIoTransformer()).subscribe(commonObserver);

    }

}
